package com.elitah.TicketAssistant;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

import android.content.Context;

public class ToolGet12306 {

	public static String requestJson(Context context, String urlPath,
			int timeout) {
		InputStream is_cer = null;
		BufferedReader reader = null;

		String failstr = new StringBuffer("{\"").append("status").append("\":")
				.append(false).append("}").toString();

		try {
			is_cer = context.getAssets().open("12306.cer");
			CertificateFactory cerFactory = CertificateFactory
					.getInstance("X.509");
			Certificate cer = cerFactory.generateCertificate(is_cer);

			KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
			keyStore.load(null, null);
			keyStore.setCertificateEntry("trust", cer);

			SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore);
			Scheme sch = new Scheme("https", socketFactory, 443);

			BasicHttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
			HttpConnectionParams.setSoTimeout(httpParams, timeout);
			HttpClient objHttpClient = new DefaultHttpClient(httpParams);
			objHttpClient.getConnectionManager().getSchemeRegistry()
					.register(sch);

			try {
				HttpGet objHttpGet = new HttpGet();
				objHttpGet.setURI(new URI(urlPath));
				HttpResponse objHttpResponse = objHttpClient
						.execute(objHttpGet);
				if (objHttpResponse.getStatusLine().getStatusCode() != 200) {
					objHttpGet.abort();
					return failstr;
				}

				reader = new BufferedReader(new InputStreamReader(
						objHttpResponse.getEntity().getContent()));
				StringBuffer objStringBuffer = new StringBuffer();
				String line = null;
				while ((line = reader.readLine()) != null) {
					objStringBuffer.append(line);
				}
				return objStringBuffer.toString();
			} catch (Exception e) {
				return failstr;
			} finally {
				if (reader != null) {
					reader.close();
				}
			}
		} catch (Exception e) {
			return failstr;
		} finally {
			try {
				if (is_cer != null) {
					is_cer.close();
				}
			} catch (IOException e) {
			}
		}
	}
}
